'use client'
import { createContext, useContext, useState, useEffect } from 'react'

// 我们会在文件末尾添加useToast钩子函数

export interface ToastProps {
  title: string
  description?: string
  status?: 'success' | 'error' | 'info' | 'warning'
  duration?: number
}

interface ToastContextProps {
  toast: (props: ToastProps) => void
  toasts: ToastProps[]
  removeToast: (index: number) => void
}

const ToastContext = createContext<ToastContextProps | undefined>(undefined)

export function ToastProvider({ children }: { children: React.ReactNode }) {
  const [toasts, setToasts] = useState<ToastProps[]>([])

  const toast = (props: ToastProps) => {
    setToasts((prevToasts) => [...prevToasts, { ...props, duration: props.duration || 3000 }])
  }

  const removeToast = (index: number) => {
    setToasts((prevToasts) => prevToasts.filter((_, i) => i !== index))
  }

  useEffect(() => {
    if (toasts.length === 0) return

    const timer = setTimeout(() => {
      removeToast(0)
    }, toasts[0].duration)

    return () => clearTimeout(timer)
  }, [toasts])

  return (
    <ToastContext.Provider value={{ toast, toasts, removeToast }}>
      {children}
      <div className="fixed top-4 right-4 z-50 space-y-2">
        {toasts.map((toast, index) => (
          <div
            key={index}
            className={`p-4 rounded-md shadow-lg ${getToastClass(toast.status)}`}
          >
            <h3 className="font-medium">{toast.title}</h3>
            {toast.description && <p className="text-sm mt-1">{toast.description}</p>}
            <button
              className="absolute top-2 right-2 text-gray-400 hover:text-gray-600"
              onClick={() => removeToast(index)}
            >
              ×
            </button>
          </div>
        ))}
      </div>
    </ToastContext.Provider>
  )
}

function getToastClass(status?: string) {
  switch (status) {
    case 'success':
      return 'bg-green-50 text-green-800 border border-green-200'
    case 'error':
      return 'bg-red-50 text-red-800 border border-red-200'
    case 'warning':
      return 'bg-yellow-50 text-yellow-800 border border-yellow-200'
    default:
      return 'bg-gray-50 text-gray-800 border border-gray-200'
  }
}

// 定义并导出useToast钩子
function useToast() {
  const context = useContext(ToastContext)
  if (context === undefined) {
    throw new Error('useToast must be used within a ToastProvider')
  }
  return context.toast
}

// 推荐用法: import { useToast } from '@/components/ui/use-toast'
// 使用方式: const toast = useToast(); toast({ title: '消息' })
export { useToast }

// 为兼容已有代码，提供默认导出
// 注意：这只是为了兼容，推荐使用命名导入
export default useToast